<template>
  <div>
    <n-modal
      v-model:show="internalShow"
      :mask-closable="false"
      preset="dialog"
      title="修改密码"
      closable
      :show-icon="false"
      :style="{
        width: '40%',
      }"
      @update:show="handleUpdateShow"
    >
      <div class="modal-content">
        <n-form ref="formRef" :model="formData" :rules="rules">
          <n-form-item label="原密码" path="oldPassword">
            <n-input 
              v-model:value="formData.oldPassword" 
              type="password" 
              placeholder="请输入原密码" 
              @blur="validateOldPassword"
              clearable
            />
          </n-form-item>
          
          <n-form-item label="新密码" path="newPassword">
            <n-input 
              v-model:value="formData.newPassword" 
              type="password" 
              placeholder="请输入新密码" 
              @input="validatePasswordMatch"
              clearable
            />
            <template #feedback>
              <div class="password-tips">
                <div :class="['tip-item', passwordStrength.level >= 1 ? 'active' : '']">
                  至少6位字符
                </div>
                <div :class="['tip-item', passwordStrength.level >= 2 ? 'active' : '']">
                  包含字母和数字
                </div>
              </div>
            </template>
          </n-form-item>
          
          <n-form-item label="确认新密码" path="confirmPassword">
            <n-input 
              v-model:value="formData.confirmPassword" 
              type="password" 
              placeholder="请再次输入新密码" 
              :status="passwordMatchStatus"
              @input="validatePasswordMatch"
              clearable
            />
            <template #feedback>
              <!-- 修复图标显示问题 -->
              <div v-if="formData.confirmPassword && !passwordsMatch" class="password-error">
                <n-icon size="16" class="icon">
                  <ErrorIcon />
                </n-icon>
                两次输入的密码不一致
              </div>
              <div v-else-if="formData.confirmPassword && passwordsMatch" class="password-success">
                <n-icon size="16" class="icon">
                  <SuccessIcon />
                </n-icon>
                密码匹配
              </div>
            </template>
          </n-form-item>
        </n-form>

        <div class="modal-actions">
          <n-button class="w-24" @click="handleCancel">取消</n-button>
          <n-button 
            class="w-24" 
            type="primary" 
            @click="handleConfirm"
            :disabled="!isFormValid"
            :loading="submitting"
          >
            {{ submitting ? '提交中...' : '确认' }}
          </n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, watch } from 'vue'
import { useMessage } from 'naive-ui'
// 确保正确引入图标
import { CheckmarkCircleOutline, CloseCircleOutline } from '@vicons/ionicons5'

export default defineComponent({
  name: 'ChangePasswordModal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:show', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage()
    
    const internalShow = ref(props.show)
    const formRef = ref(null)
    const submitting = ref(false)
    
    const formData = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 在 setup 中返回图标组件
    const SuccessIcon = CheckmarkCircleOutline
    const ErrorIcon = CloseCircleOutline
    
    watch(() => props.show, (newVal) => {
      internalShow.value = newVal
    })
    
    const passwordsMatch = computed(() => {
      return formData.newPassword === formData.confirmPassword && formData.newPassword !== ''
    })
    
    const passwordMatchStatus = computed(() => {
      if (!formData.confirmPassword) return null
      return passwordsMatch.value ? 'success' : 'error'
    })
    
    const passwordStrength = computed(() => {
      const password = formData.newPassword
      if (!password) return { level: 0, text: '' }
      
      let level = 0
      if (password.length >= 6) level = 1
      if (/[a-zA-Z]/.test(password) && /[0-9]/.test(password)) level = 2
      if (/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)) level = 3
      
      return { level }
    })
    
    const isFormValid = computed(() => {
      return passwordsMatch.value && 
             formData.oldPassword && 
             formData.newPassword && 
             formData.confirmPassword &&
             passwordStrength.value.level >= 1
    })
    
    const rules = {
      // ... 规则保持不变
    }
    
    const validatePasswordMatch = () => {
      if (formRef.value) {
        formRef.value.validate((errors) => {})
      }
    }
    
    const validateOldPassword = () => {
      if (formRef.value) {
        formRef.value.validate((errors) => {})
      }
    }
    
    const handleUpdateShow = (value) => {
      internalShow.value = value
      emit('update:show', value)
      if (!value) {
        resetForm()
      }
    }
    
    const handleCancel = () => {
      internalShow.value = false
      emit('update:show', false)
      resetForm()
      message.info('已取消修改密码')
    }
    
    const handleConfirm = async () => {
      if (formRef.value) {
        formRef.value.validate(async (errors) => {
          if (!errors) {
            submitting.value = true
            try {
              await new Promise(resolve => setTimeout(resolve, 1000))
              emit('confirm', {
                oldPassword: formData.oldPassword,
                newPassword: formData.newPassword
              })
              message.success('密码修改成功！')
              resetForm()
              internalShow.value = false
              emit('update:show', false)
            } catch (error) {
              message.error('密码修改失败，请重试')
              console.error('密码修改失败:', error)
            } finally {
              submitting.value = false
            }
          } else {
            message.warning('请检查表单填写是否正确')
          }
        })
      }
    }
    
    const resetForm = () => {
      formData.oldPassword = ''
      formData.newPassword = ''
      formData.confirmPassword = ''
      if (formRef.value) {
        formRef.value.restoreValidation()
      }
    }
    
    return {
      internalShow,
      formRef,
      formData,
      rules,
      passwordsMatch,
      passwordMatchStatus,
      passwordStrength,
      isFormValid,
      submitting,
      SuccessIcon,  // 返回图标
      ErrorIcon,    // 返回图标
      validatePasswordMatch,
      validateOldPassword,
      handleUpdateShow,
      handleCancel,
      handleConfirm
    }
  }
})
</script>

<style scoped>
/* 样式保持不变 */
.modal-content {
  padding: 10px 0;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.w-24 {
  width: 96px;
}

.password-error {
  color: #d03050;
  font-size: 12px;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.password-success {
  color: #18a058;
  font-size: 12px;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.password-tips {
  display: flex;
  gap: 12px;
  margin-top: 4px;
}

.tip-item {
  font-size: 12px;
  color: #c0c4cc;
  transition: color 0.3s;
}

.tip-item.active {
  color: #18a058;
}

.icon {
  margin-right: 4px;
}
</style>